package cn.itsource.hbc.user.service.impl;

import cn.itsource.basic.service.impl.BaseServiceImpl;
import cn.itsource.hbc.user.contants.UserContants;
import cn.itsource.hbc.user.domain.LoginInfo;
import cn.itsource.hbc.user.domain.User;
import cn.itsource.hbc.user.domain.dto.UserDto;
import cn.itsource.hbc.user.mapper.LoginInfoMapper;
import cn.itsource.hbc.user.mapper.UserMapper;
import cn.itsource.hbc.user.service.IUserService;
import cn.itsource.utils.MD5Utils;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private LoginInfoMapper loginInfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void register(UserDto userDto) {

        // 取出redis中的验证码包括时间搓
        String codeInRedis =(String)redisTemplate.opsForValue().get(UserContants.REGISTER_CODE+":"+userDto.getPhone());
        // 取出code
        String code = codeInRedis.split(":")[0];
        if (!code.equals(userDto.getCode())){

            throw new RuntimeException("验证码有误");
        }
       User user = userDto2User(userDto);

        userMapper.save(user);

       LoginInfo loginInfo = user2LoginInfo(user);

        loginInfoMapper.save(loginInfo);

    }

    @Override
    public User loadByPhone(String phone) {
        return userMapper.loadByPhone(phone);
    }



    @Override
    public LoginInfo login(User user) {
        // 获取用户名密码
        LoginInfo loginInfo = loginInfoMapper.login(user.getUsername());
        // 当用户没有输入用户名的时候抛异常

        if(loginInfo==null){

            throw new RuntimeException("用户名或密码错误");

        }
        String md5 = MD5Utils.encrypByMd5(user.getPassword() + loginInfo.getSalt());
        if(!md5.equals(loginInfo.getPassword())){
            throw new RuntimeException("用户名或密码错误");


        }
            return loginInfo;



    }

    private LoginInfo user2LoginInfo(User user) {

        LoginInfo loginInfo = new LoginInfo();
        BeanUtils.copyProperties(user,loginInfo);
        loginInfo.setDisable(1);
        loginInfo.setType(1);
        loginInfo.setUId(user.getId());
        return loginInfo;
    }


    private User userDto2User(UserDto userDto) {

        User user = new User();
        user.setPhone(userDto.getPhone());
        // 盐值
        String salt = UUID.randomUUID().toString();
        // 密码拼接盐值，进行加密
        String md5 = MD5Utils.encrypByMd5(userDto.getPassword() + salt);
        user.setState(1);
        user.setSalt(salt);
        user.setPassword(md5);
        return user;
    }
}
